package cat.music.ut.comm.viewutils


import android.content.Context
import android.graphics.Bitmap
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur

object BlurUtils {
    fun blurBitmap(
        context: Context?,
        orig: Bitmap,
        radius: Float,
        scale: Float,
        sb: StringBuilder
    ): Bitmap {
        val cur = System.currentTimeMillis()
        sb.append("image" + orig.width + " * " + orig.height)
        sb.append("\n")
        sb.append("bur $radius")
        sb.append("\n")
        // 计算图片缩小后的长宽
        val targetW = Math.round(orig.width * scale)
        val targetH = Math.round(orig.height * scale)

        val input = Bitmap.createScaledBitmap(orig, targetW, targetH, false)
        val out = Bitmap.createBitmap(input)

        val rs = RenderScript.create(context)
        val script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs))

        val tmpIn = Allocation.createFromBitmap(rs, input)
        val tmpOut = Allocation.createFromBitmap(rs, out)

        // 设置模糊程度
        script.setRadius(radius)
        script.setInput(tmpIn)
        script.forEach(tmpOut)

        tmpOut.copyTo(out)
        sb.append("time " + (System.currentTimeMillis() - cur))
        return out
    }
}